package iq.lucene;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;


public class Test {

	/**
	 *  建立索引
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		String srcDir = "D:/Documents and Settings/My Documents/javascript";
		String distDir = "c:/indexWriter";

		Directory dir = null;
		dir = new SimpleFSDirectory(new File(distDir));

		IndexWriter indexWriter = new IndexWriter(dir, new StandardAnalyzer(
				Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);
		
		for (File f : new File(srcDir).listFiles()) {
			if (!f.getName().endsWith(".txt")) {
				continue;
			}
			Document doc = new Document();
			doc.add(new Field("contents", new FileReader(f)));
			doc.add(new Field("filename", f.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
			doc.add(new Field("indexDate", DateTools.dateToString(new Date(), DateTools.Resolution.DAY), Field.Store.YES, Field.Index.NOT_ANALYZED));
			
			indexWriter.addDocument(doc);
		}
		System.out.println(indexWriter.numDocs());
		indexWriter.close();

	}

}

class Test2{
	/**
	 * 搜索索引
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws IOException, ParseException {
		String distDir = "c:/indexWriter";

		Directory dir = null;
		dir = new SimpleFSDirectory(new File(distDir));
		
		IndexSearcher indexSearcher = new IndexSearcher(dir);
		
		QueryParser queryParser = new QueryParser(Version.LUCENE_30, "contents", new StandardAnalyzer(
				Version.LUCENE_30));
		
		Query query = queryParser.parse("内");
		
		TopDocs topDocs = indexSearcher.search(query, 5);
		
		System.out.println("搜索到了" + topDocs.totalHits + "个结果");
		
		for (int i=0; i<topDocs.scoreDocs.length;i++) {
			ScoreDoc scoreDoc = topDocs.scoreDocs[i];
			Document doc = indexSearcher.doc(scoreDoc.doc);
			System.out.println(doc.get("filename"));
		}
		
		indexSearcher.close();
	}
}

class DataBaseIndexer {
	public static void main(String[] args) throws IOException, SQLException,
			ClassNotFoundException {
		String indexDir = "c:/indexWriter";

		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager
				.getConnection(
						"jdbc:mysql://192.168.0.102:3306/dianyiwang?characterEncoding=utf8",
						"dianyiwang", "dianyiwang");

		Statement stmt = conn.createStatement();

		ResultSet rs = stmt.executeQuery("select * from t_disease_art");
		// 为表字段建立索引
		Directory dir = new SimpleFSDirectory(new File(indexDir));
		IndexWriter indexWriter = new IndexWriter(dir, new StandardAnalyzer(
				Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);
		while (rs.next()) {
			System.out.println(rs.getString("id"));
			Document doc = new Document();
			doc.add(new Field("id", rs.getString("id"), Field.Store.YES,
					Field.Index.NOT_ANALYZED));
			doc.add(new Field("DISEASE_REASON", rs.getString("DISEASE_REASON")==null?"":rs.getString("DISEASE_REASON"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("DISEASE_ZHENGZHUANG", rs.getString("DISEASE_ZHENGZHUANG")==null?"":rs.getString("DISEASE_ZHENGZHUANG"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("DISEASE_HUAYAN", rs.getString("DISEASE_HUAYAN")==null?"":rs.getString("DISEASE_HUAYAN"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("DISEASE_JIANBIE", rs.getString("DISEASE_JIANBIE")==null?"":rs.getString("DISEASE_JIANBIE"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("DISEASE_BINGFA", rs.getString("DISEASE_BINGFA")==null?"":rs.getString("DISEASE_BINGFA"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("DISEASE_YUFAN", rs.getString("DISEASE_YUFAN")==null?"":rs.getString("DISEASE_YUFAN"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("DISEASE_ZILIAO", rs.getString("DISEASE_ZILIAO")==null?"":rs.getString("DISEASE_ZILIAO"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("DISEASE_ZHENGHOU", rs.getString("DISEASE_ZHENGHOU")==null?"":rs.getString("DISEASE_ZHENGHOU"),
					Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("indexDate", DateTools.dateToString(new Date(),
					DateTools.Resolution.DAY), Field.Store.YES,
					Field.Index.NOT_ANALYZED));
			indexWriter.addDocument(doc);
		}
		System.out.println("numDocs" + indexWriter.numDocs());
		indexWriter.close();
		
		rs.close();
		stmt.close();
		conn.close();
	}
}

class ReadDataBaseIndex {
	/**
	 * 搜索索引
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws IOException, ParseException {
		long startTime = System.currentTimeMillis();
		String distDir = "c:/indexWriter";

		Directory dir = null;
		dir = new SimpleFSDirectory(new File(distDir));
		
		IndexSearcher indexSearcher = new IndexSearcher(dir);
		
		QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_30, new String[]{"DISEASE_REASON", "DISEASE_ZHENGZHUANG", "DISEASE_HUAYAN", "DISEASE_JIANBIE", "DISEASE_BINGFA", "DISEASE_YUFAN", "DISEASE_ZILIAO", "DISEASE_ZHENGHOU"}, new StandardAnalyzer(
				Version.LUCENE_30));
		Query query = queryParser.parse("郁闷");
		TopDocs topDocs = indexSearcher.search(query, 200);
		
		System.out.println("搜索到了" + topDocs.totalHits + "个结果");
		
		for (int i=0; i<topDocs.scoreDocs.length;i++) {
			ScoreDoc scoreDoc = topDocs.scoreDocs[i];
			Document doc = indexSearcher.doc(scoreDoc.doc);
			System.out.println(doc.get("id"));
		}
		System.out.println("time: " + (System.currentTimeMillis()-startTime) + "ms");
		indexSearcher.close();
		
		//使用jdbc直接读
		Connection conn = null;
		try {
			startTime = System.currentTimeMillis();
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
							"jdbc:mysql://192.168.0.102:3306/dianyiwang?characterEncoding=utf8",
							"dianyiwang", "dianyiwang");

			PreparedStatement stmt = conn.prepareStatement("select * from t_disease_art where DISEASE_REASON like ? or DISEASE_ZHENGZHUANG like ? or DISEASE_HUAYAN like ? or DISEASE_JIANBIE like ? or DISEASE_BINGFA like ? or DISEASE_YUFAN like ? or DISEASE_ZILIAO like ? or DISEASE_ZHENGHOU like ? ");
			String likeStr = "%郁闷%";
			for (int i=0;i<8;i++) {
				stmt.setString(i+1, likeStr);
			}
			
			ResultSet rs = stmt.executeQuery();
			int count = 0;
			while (rs.next()){
				System.out.println(rs.getString("id"));
				count++;
			}
			System.out.println("搜索到了" + count + "个结果");
			System.out.println("time: " + (System.currentTimeMillis()-startTime) + "ms");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}